package com.azusa.xbjy.controller;

import com.azusa.xbjy.entity.Result;
import com.azusa.xbjy.entity.StatusCode;
import com.azusa.xbjy.entity.User;
import com.azusa.xbjy.service.UserService;
import com.azusa.xbjy.utils.IdWorker;
import com.azusa.xbjy.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${file.uploadFolder}")
    private String realBasePath;     //文件上传真实路径
    @Value("${file.accessPath}")
    private String accessPath;      //虚拟路径
    @Value("${server.servlet.context-path}")
    private String contextPath;     //上下文

    @RequestMapping("toDetail")
    public ModelAndView toDetail(){
        return new ModelAndView("user/user_detail");
    }

    @RequestMapping("toUserLook")
    public ModelAndView toUserLook(){
        return new ModelAndView("user/user_look");
    }

    @RequestMapping("toUser")
    public ModelAndView toUser(){
        return new ModelAndView("user/user");
    }

    @RequestMapping("toUserDetail")
    public ModelAndView toUserDetail(){
        return new ModelAndView("user/user_detail");
    }

    @RequestMapping("toMyUser")
    public ModelAndView toMyUser(){
        return new ModelAndView("user/my_user");
    }

    /**
     * 根据id查询个人用户
     * @param id
     * @return
     */
    @RequestMapping("findUserLookById/{id}")
    public Result findUserLookById(@PathVariable("id") int id){
        return new Result(StatusCode.SUCCESS,userService.findUserLookById(id));
    }

    /**
     * 修改个人用户信息
     * @param user
     * @param session
     * @return
     */
    @PutMapping("doUpdate")
    public Result doUpdate(@RequestBody User user, HttpSession session) {
        User updateUser = userService.save(user);
        session.setAttribute("loginUser",updateUser);
        return new Result(StatusCode.SUCCESS,updateUser);
    }

    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     */
    @RequestMapping("upload/{id}")
    public Result upload(@RequestParam("file") MultipartFile file, @PathVariable("id") int userId, HttpServletRequest request){
        //获取请求地址
        String origin = request.getHeader("Origin");
        //获取文件名
        String oldFileName = file.getOriginalFilename();
        String suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")+1);
        if ("jpg".equals(suffixName) || "gif".equals(suffixName) || "png".equals(suffixName) || "jpeg".equals(suffixName)){ //...一系列判断
            String newFileName = UUID.randomUUID() + "-" + oldFileName;
            // 域名访问的相对路径（通过浏览器访问的链接-虚拟路径）
            String saveToPath = origin + contextPath + accessPath;
            // 真实路径，实际储存的路径
            String realPath = realBasePath;
            // 储存文件的物理路径，使用本地路径储存
            String filepath = realPath + newFileName;
            File path = new File(filepath);
            //目录不存在则创建
            if (!path.getParentFile().exists()){
                path.getParentFile().mkdir();
            }
            try {
                //写入文件
                file.transferTo(path);
                //修改上传的用户其pic记录的文件位置
                User user = userService.findUserLookById(userId);
                user.setPic(saveToPath + newFileName);
                User u = userService.save(user);
                return new Result(StatusCode.SUCCESS,u);
            } catch (Exception e) {
                return new Result(StatusCode.ERROR,"上传失败");
            }
        }else {
            return new Result(StatusCode.ERROR,"上传的文件不是图片格式");
        }
    }

    /**
     * 用户列表查询模块
     * @param pageNum
     * @param pageSize
     * @param map
     * @param session
     * @return
     */
    @RequestMapping(value = "findUserPage/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Result findUserPageLikeUsername(@PathVariable("pageNum")int pageNum,@PathVariable("pageSize")int pageSize,@RequestBody Map<String,Object> map,HttpSession session){
        User user = LoginUserUtil.getLoginUser();
        assert user != null;
        if (map.containsKey("keywords")){
            return new Result(StatusCode.SUCCESS,userService.findAllPage(pageNum, pageSize, (String) map.get("keywords"),user.getId()));
        }
        return new Result(StatusCode.SUCCESS,userService.findAllPage(pageNum, pageSize, "",user.getId()));
    }

    /**
     * 关注/取消关注用户
     * @param map
     * @param session
     * @return
     */
    @PutMapping("changeFocused")
    public Result changeFocused(@RequestBody Map<String,Object> map,HttpSession session){
        if (map.containsKey("focus") && map.containsKey("userId")){
            Boolean focus = (Boolean) map.get("focus");
            Integer userId = (Integer) map.get("userId");
            User user = LoginUserUtil.getLoginUser();
            userService.changeFocused(user.getId(),userId,focus);
            return new Result(StatusCode.SUCCESS);
        }
        return new Result(StatusCode.ERROR);
    }

    /**
     * 根据修改被看数
     * @param id
     * @return
     */
    @PutMapping("updateLook/{userId}")
    public Result updateLook(@PathVariable("userId")int id){
        userService.updateLook(id);
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 查询我的关注中的用户列表信息
     * @param pageNum
     * @param pageSize
     * @param id
     * @return
     */
    @RequestMapping("findMyUser/{pageNum}/{pageSize}/{id}")
    public Result findMyUser(@PathVariable("pageNum")int pageNum,@PathVariable("pageSize")int pageSize,@PathVariable("id")int id){
        return new Result(StatusCode.SUCCESS,userService.findMyUser(pageNum,pageSize,id));
    }

    /**
     * 根据部门id查询用户列表
     * @param deptId
     * @return
     */
    @RequestMapping("findUserByDeptId/{deptId}")
    public Result findUserByDeptId(@PathVariable("deptId")int deptId){
        return new Result(StatusCode.SUCCESS,userService.findByDeptId(deptId));
    }

    /**
     * 修改用户密码
     * @param code
     * @param params
     * @return
     */
    @RequestMapping("updatePassword/{code}")
    public Result updatePassword(@PathVariable("code")String code,@RequestBody Map<String,String> params){
        String email = params.get("email");
        String checkCode = (String) redisTemplate.opsForValue().get("code:" + email);
        if (checkCode !=null && checkCode.equals(code)){
            User user = userService.findByEmail(params.get("email"));
            user.setPassword(params.get("password"));
            userService.save(user);
            return new Result(StatusCode.SUCCESS);
        }else {
            return new Result(StatusCode.SUCCESS,"验证码信息错误，请重新发送");
        }
    }
}
